package com.example.spider.common.handler;

import com.example.spider.common.task.SpiderTask;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * 新浪结果处理器
 * @author lym
 */
@Slf4j
public class SpiderResultHandlerManager {

    private final Executor executor;

    private final List<SpiderResultHandler> resultHandlers;

    public SpiderResultHandlerManager(List<SpiderResultHandler> resultHandlers, Executor executor) {
        this.resultHandlers = resultHandlers;
        this.executor = executor;
    }

    public void handle(SpiderTask task, String result) {
        if(resultHandlers == null){
            return;
        }
        log.info("handle spiderTask " + task.getUrl());
        executor.execute(() ->
            resultHandlers.forEach(handler -> {
                if(handler.canHandle(task, result)){
                    handler.handle(task, result);
                }
            })
        );
        log.info("finish handle spiderTask " + task.getUrl());
    }


}
